/*
 * Copyright (C) 2011 Wglxy.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tigerlee.candle.activity;

import java.io.IOException;
import java.io.InputStream;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tigerlee.candle.R;
import com.tigerlee.candle.client.ChatClientService;
import com.tigerlee.candle.spreadsheet.ChatServerFeedParser;
import com.tigerlee.candle.spreadsheet.ChatServerParsedData;
import com.tigerlee.candle.spreadsheet.MyHttpRequest;
import com.tigerlee.candle.util.Constants;
import com.tigerlee.candle.util.SharedPreference;

/**
 * This is the activity for feature 1 in the dashboard application. It displays
 * some text and provides a way to get back to the home activity.
 * 
 */

public class ChatActivity extends ManagerActivity implements OnClickListener {
	// All View of this activity.
	private TextView mNumUsersText;
	private EditText mEditText;
	private ListView mListView;
	private Button mSendButton;

	// Client thread for chatting
	private ChatClientService mChatClientService;

	// Chatting nickname
	public String mChatName = null;

	// Array adapter for the conversation thread
	private ArrayAdapter<String> mConversationArrayAdapter;

	private int mPort = Constants.mKoreanChatPort;
	private SharedPreference mSharedPreference;

	private Boolean mIsConnected = false;

	private final static int SET_LANGUAGE = 1;
	private final static int NAME_DIALOG = 2;
	private final static int EXIT_DIALOG = 3;

	// public static final int MESSAGE_WRITE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_TOAST = 3;

	private static String JOIN_MSG = null;

	public static final String TAG = "ChattingClient";
	public static final String TOAST = "toast";

	private static int mNumUser = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_activity);

		setupView();

		// Refer to preference to check showing dialog or not.
		mSharedPreference = new SharedPreference(this);
		if (mSharedPreference.getShowChatDialog() == false) {
			showNameDialog();
		} else {
			mChatName = mSharedPreference.getChatname();
			if (mChatName == null || mChatName.equals("")) {
				toast(getString(R.string.toast_fail_get_nickname),
						Toast.LENGTH_SHORT);
				finish();
			} else {
				super.startDialog();
				connectServer();
			}
		}

	}

	private void setupView() {
		// Initialize the array adapter for the conversation thread
		mConversationArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.message);
		mNumUsersText = (TextView) findViewById(R.id.chat_numusers);
		mListView = (ListView) findViewById(R.id.chat_listview);
		mListView.setAdapter(mConversationArrayAdapter);		
		mConversationArrayAdapter.clear();

		mEditText = (EditText) findViewById(R.id.input_edittext);
		mSendButton = (Button) findViewById(R.id.send_button);
		mSendButton.setOnClickListener(this);

		JOIN_MSG = getString(R.string.text_join);
		mChatClientService = new ChatClientService(this, mHandler);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case SET_LANGUAGE:
			// showDialog(NAME_DIALOG);
			break;
		/*
		 * final CharSequence[] items = { getString(R.string.dialog_language_1),
		 * getString(R.string.dialog_language_2),
		 * getString(R.string.dialog_language_3)}; AlertDialog.Builder
		 * mLanguageDialog = new AlertDialog.Builder(this);
		 * mLanguageDialog.setTitle(getString(R.string.title_language));
		 * mLanguageDialog.setSingleChoiceItems(items, -1, new
		 * DialogInterface.OnClickListener() { public void
		 * onClick(DialogInterface dialog, int item) { switch (item) { case 0:
		 * mPort = Constants.mEnglishChatPort; break; case 1: mPort =
		 * Constants.mSpanishChatPort; break; case 2: mPort =
		 * Constants.mKoreanChatPort; break; default: break; } dialog.dismiss();
		 * showDialog(NAME_DIALOG); } }); return mLanguageDialog.create();
		 */
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showExitDialog();
	}
	private void showNameDialog(){
		Intent i = new Intent(this, CustomDialogEditActivity.class);
		startActivityForResult(i, NAME_DIALOG);
	}

	private void showExitDialog() {
		// TODO Auto-generated method stub
		Intent i = new Intent(this, CustomDialogButtonActivity.class);
		i.putExtra(Intent.EXTRA_TEXT, getString(R.string.text_exit_dialog));
		startActivityForResult(i, EXIT_DIALOG);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == EXIT_DIALOG){
			if(resultCode == RESULT_OK){
				if (mIsConnected == true) {
					mChatClientService.write("exit");
					mChatClientService.disconnectServer();
				}
				finish();
			}
		}else if(requestCode ==NAME_DIALOG){
			if(resultCode == RESULT_OK){
				mChatName = mSharedPreference.getChatname();
				startDialog();
				connectServer();
			}else{
				finish();
			}
		}
	}

	// The Handler that gets information back from the BluetoothChatService
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_READ:
				String readString = (String) msg.obj;
				try {
					if (readString.startsWith("+") == true) {
						if(readString.startsWith("++") == true){
							mNumUser++;
							mConversationArrayAdapter.add(readString.substring(2));
						}else{
							mNumUser = Integer.valueOf(readString.substring(1));
						}
						mNumUsersText.setText(getApplicationContext().getString(R.string.text_numusers) 
								+ " " + mNumUser);
					} else if (readString.startsWith("--") == true) {
						mNumUser--;
						mNumUsersText.setText(getApplicationContext().getString(R.string.text_numusers) 
								+ " " + mNumUser);
					} else {
						// construct a string from the valid bytes in the buffer
						mConversationArrayAdapter.add(readString);
						// mListView.getChildAt(mListView.getCount()-1).setBackgroundColor(R.color.red);
					}
				} catch (NullPointerException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	};

	public void connectServer() {
		// Check to connect twice.. that causes to run thread twice.
		if (mIsConnected == true)
			return;

		new Thread(new Runnable() {
			public void run() {
				// 1. get Server IP, Port
				MyHttpRequest mHttpRequests = new MyHttpRequest();
				InputStream mInputStream = null;
				try {
					mInputStream = mHttpRequests.getHttpStream(Constants.mServerFeedUrl);
					if (mInputStream != null) {
						ChatServerFeedParser mServerFeedParser = new ChatServerFeedParser();
						if (mServerFeedParser.getParedData(mInputStream) == true) {
							Log.e("!!", "ChatServerFeedParser true");
							// TODO: get Chat Port by language.
							for (int i = 0; i < ChatServerParsedData.index; i++) {
								String language = ChatServerParsedData.mLanguageServer.get(i);
								if (language.startsWith("3") == true) {
									Constants.mChatServerIP = ChatServerParsedData.mIPServer.get(i);
									mPort = ChatServerParsedData.mPortServer.get(i);
								}
							}
							// 3. connect to server
							if (mChatClientService.connectServer(mPort) == false) {
								setOK(false, getString(R.string.toast_fail_join_chat));
							} else {
								//only successful point to finish progress dialog
								setOK(true, null);
								mIsConnected = true;
								mChatClientService.write("++" + mChatName + " "
										+ JOIN_MSG);
							}
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				} catch (NullPointerException e) {
					e.printStackTrace();
					return;
				}
			}
		}).start();
		if (mChatName == null || mChatName.equals("")) {
			toast(getString(R.string.toast_fail_get_nickname),
					Toast.LENGTH_SHORT);
			finish();
			return;
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.send_button:
			String mMessage = mEditText.getText().toString();
			if (mMessage == null || mMessage.equals("")
					|| mIsConnected == false) {
				break;
			} else {
				mChatClientService.write(mChatName + ": " + mMessage);
				mEditText.setText("");
			}
			break;

		default:
			break;
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
} // end class
